package expression;

import java.util.ArrayList;
import java.util.List;

import choco.integer.IntExp;

import common.MCore;

public class MSum extends MBasicExpr {

	public MSum(MCore c) {
		super(c);
	}

	public IntExp intExp() {
		List<IntExp> vars = new ArrayList<IntExp>();
		MSumCst cst = new MSumCst(getCore());
		
		for (MIntExpr i: getParameters()) {
			if (i instanceof MIntExprCst) {
				cst.getParameters().add((MIntExprCst)i);
			}
			else {
				vars.add(i.intExp());
			}
		}
		IntExp[] temp = new IntExp[0];
		temp = vars.toArray(temp);
		return getCore().getProblem().plus(cst.compute(), getCore().getProblem().sum(temp));
	}

	public String toText() {
		String s = "(+";
		for (MIntExpr i: getParameters()) {
			s += " " + i.toText();
		}
		s += ")";
		
		return s;
	}

	public MIntExpr eval() {
		int val = 0;
		MSum sum = new MSum(getCore());
		
		for (MIntExpr i: getParameters()) {
			MExpr exp = i.eval();
			if (exp instanceof MIntCst) {
				val += ((MIntCst)exp).compute();
			}
			else {
				sum.getParameters().add(i);
			}
		}

		if (sum.getParameters().size() > 0) {
			sum.getParameters().add(new MIntCst(getCore(), val));
			return sum;
		}
		else {
			return new MIntCst(getCore(), val);
		}
	}
}
